﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.Mvc;
using OpenQuarters.WebQuarters.Core;
using LinqToTwitter;
using OpenQuarters.WebQuarters.Utils;

namespace OpenQuarters.WebQuarters.Modules.Twitter
{
    public class TwitterModule : Module
    {
        public static Dictionary<string, string> Templates
        {
            get
            {
                var d = new Dictionary<string, string>();
                d.Add("", "[Default]");
                foreach (var dir in new DirectoryInfo(Oracle.Context.Server.MapPath("~/Templates/")).GetDirectories())
                {
                    if (dir.Name.Contains(typeof(TwitterModule).FullName))
                    {
                        foreach (var template in dir.GetFiles("*.ascx", SearchOption.TopDirectoryOnly))
                        {
                            d.Add(template.Name.Replace(".ascx", ""), template.Name.Replace(".ascx", ""));
                        }
                    }
                }
                return d;
            }
        }

        private string template = "";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown, OptionSource = "OpenQuarters.WebQuarters.Modules.Twitter.TwitterModule.Templates")]
        public string Template
        {
            get { return template; }
            set { template = value; }
        }
        
        private string account = "";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string Account
        {
            get { return account; }
            set { account = value; }
        }

        private int count = 5;

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public int Count
        {
            get { return count; }
            set { count = value; }
        }

        private bool updatesOnly = false;

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.CheckBox)]
        public bool UpdatesOnly
        {
            get { return updatesOnly; }
            set { updatesOnly = value; }
        }

        public override void Initialise()
        {
            this.ModuleName = "Twitter Module";
            this.ModuleDescription = "Places a Twitter feed on the page.";
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try
            {

                var twitterCtx = new TwitterContext();

                List<Status> tweets = null;

                if (account.Length != 0)
                {
                    if (updatesOnly)
                    {
                        try
                        {
                            // Attempt 1
                            var lookup = (from tweet in twitterCtx.Status
                                          where tweet.Type == StatusType.User
                                          && tweet.ID == account
                                          && tweet.Count == 200
                                          select tweet).ToList();

                            tweets = lookup.Where(tweet => tweet.InReplyToScreenName.Length == 0 && tweet.InReplyToStatusID.Length == 0 && tweet.InReplyToUserID.Length == 0).Take(count).ToList();
                        }
                        catch
                        {
                            // Attempt 2
                            try
                            {
                                var lookup = (from tweet in twitterCtx.Status
                                              where tweet.Type == StatusType.User
                                              && tweet.ID == account
                                              && tweet.Count == 200
                                              select tweet).ToList();

                                tweets = lookup.Where(tweet => tweet.InReplyToScreenName.Length == 0 && tweet.InReplyToStatusID.Length == 0 && tweet.InReplyToUserID.Length == 0).Take(count).ToList();
                            }
                            catch
                            {
                                // Attempt 3
                                try
                                {
                                    var lookup = (from tweet in twitterCtx.Status
                                                  where tweet.Type == StatusType.User
                                                  && tweet.ID == account
                                                  && tweet.Count == 200
                                                  select tweet).ToList();

                                    tweets = lookup.Where(tweet => tweet.InReplyToScreenName.Length == 0 && tweet.InReplyToStatusID.Length == 0 && tweet.InReplyToUserID.Length == 0).Take(count).ToList();
                                }
                                catch
                                {
                                    throw new ApplicationException("There was an error receiving the Twitter feed");
                                }

                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            // Attempt 1
                            tweets = (from tweet in twitterCtx.Status
                                      where tweet.Type == StatusType.User
                                      && tweet.ID == account
                                      && tweet.Count == count
                                      select tweet).ToList();
                        }
                        catch
                        {
                            try
                            {
                                // Attempt 2
                                tweets = (from tweet in twitterCtx.Status
                                          where tweet.Type == StatusType.User
                                          && tweet.ID == account
                                          && tweet.Count == count
                                          select tweet).ToList();
                            }
                            catch
                            {
                                try
                                {
                                    // Attempt 3
                                    tweets = (from tweet in twitterCtx.Status
                                              where tweet.Type == StatusType.User
                                              && tweet.ID == account
                                              && tweet.Count == count
                                              select tweet).ToList();
                                }
                                catch
                                {
                                    throw new ApplicationException("There was an error receiving the Twitter feed");
                                }
                            }
                        }
                    }
                }

                if (this.Template.Length == 0)
                {
                    this.Controls.Add(new LiteralControl("No template selected"));
                }
                else
                {
                    var viewPath = "~/Templates/" + this.GetType().FullName + "/" + this.Template + ".ascx";
                    //this.Controls.AddLiteral(GeneralUtils.RenderViewToString(
                    //        Oracle.CurrentControllerContext,
                    //        viewPath,
                    //        null,
                    //        new ViewDataDictionary(tweets),
                    //        new TempDataDictionary()));
                    this.Controls.AddLiteral(GeneralUtils.RenderPartialToString(viewPath, tweets));
                }
            }
            catch (ApplicationException ex)
            {
                this.Controls.Add(new LiteralControl(ex.Message));
            }
        }
    }
}
